package org.aseclipse.osgi.container;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ASBundleServlet extends HttpServlet{

	private static final Log log_ = LogFactory.getLog(ASBundleServlet.class);
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//resp.setContentType("text/html");
		//resp.getWriter().println("<h3>Hello from HelloWorldServlet</h3>");
		String query = req.getRequestURI();
		if(log_.isDebugEnabled())
			log_.debug(">>> RequestURI: " + query);
		String[] resources = getResources(query);
		byte[] cache = null;
		if(resources != null) {
			if(log_.isDebugEnabled())
				log_.debug(">>> resources[0]: " + resources[0] + ", resources[1]: " + resources[1]);
			if(resources[0].indexOf(".") != -1) { // /osgi/${bundle.name}/${file.name}
				cache = ASBundleManager.getInstance().loadResource(resources[0], resources[1], req.getParameterMap());
			} else { // /osgi/extenders/${bundle.name} or /osgi/requires/${bundle.name}
				if("extenders".equalsIgnoreCase(resources[0]))
					cache = ASBundleManager.getInstance().loadExtenderPlugins(resources[1], req.getParameterMap());
				else if ("requires".equalsIgnoreCase(resources[0]))
					cache = ASBundleManager.getInstance().loadRequiredPlugins(resources[1], req.getParameterMap());
			}
		}
		if(cache == null) {
			cache = "No Resource".getBytes();
		}
		if(resources[1].endsWith(".swf")) {
			resp.setContentType("application/x-shockwave-flash;ISO-8859-1");
            //response.getWriter().write(new String(buffer, "ISO-8859-1"));
        }
		synchronized(this) {
			try {
				OutputStream outStream = resp.getOutputStream();
				//String content= new String(cache);
				// resp.setContentLength(content.length());
				resp.setHeader("Content-Length", ""+cache.length);
				//resp.getWriter().println(content);
		        if(log_.isDebugEnabled())
		        	log_.debug("File size: " + cache.length);
		        outStream.write(cache);
		        outStream.close();
		        cache = null;
			} catch(Exception ex) {
				log_.debug("Fail to write response");
			}
		}
	}
	
	private String[] getResources(String query) {
		int loc = query.indexOf("/");
		if(loc != -1) {
			loc = query.indexOf("/", loc + 1);
			if(loc != -1) {
				loc = query.indexOf("/", loc + 1);
			}
		}
		if(loc != -1) {
			String resource = query.substring(loc + 1);
			//log_.info(">>> resource: " + resource);
			loc = resource.indexOf("/");
			if(loc != -1) {
				String[] result = new String[2];
				result[0] = resource.substring(0, loc);
				String value = resource.substring(loc + 1);
				if((loc = value.indexOf("?")) != -1) {
					value = value.substring(0, loc);
				}
				result[1] = value;
				//log_.info(">>> bundle: " + result[0] + ", resource: " + result[1]);
				return result;
			}
		}
		return null;
	}

}
